package org.scboy.coobi.sql.factory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import org.scboy.coobi.sql.Coobi;
import org.scboy.coobi.sql.SqlEntity;
import org.scboy.coobi.sql.proxy.MethodProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EntityFactory {
	
	@Autowired
	Coobi coobi;
	
	/**
	 * 构建代理
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getDao(Class<T> clazz) {

		//检查传入对象
		if(Object.class.equals(clazz.getDeclaringClass())) {
			throw new RuntimeException("传入对象必须是接口。");
		}
		MethodProxy invocationHandler=new MethodProxy(coobi, clazz,null);
		//构建方法代理及实例
		Object newProxyInstance=Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, (InvocationHandler) invocationHandler);
		
		//返回接口动态实现的实例
		return (T)newProxyInstance;
	}
	
	public SqlEntity getDao(String tableName) {
		
		Class<SqlEntity> clazz=SqlEntity.class;
		MethodProxy invocationHandler=new MethodProxy(coobi, clazz,tableName);
		//构建方法代理及实例
		Object newProxyInstance=Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, (InvocationHandler) invocationHandler);
		
		//返回接口动态实现的实例
		return (SqlEntity)newProxyInstance;
	}
}
